package com.warm.androidstudy.view.ratingBar;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;

import androidx.annotation.Nullable;

import com.warm.androidstudy.R;

/**
 * 自定义评分控件
 * @author DELL
 */
public class RatingBarView extends View {

    /**
     * 星星的宽度
     */
    private float mStarWidth;
    /**
     * 星星的高度
     */
    private float mStarHeight;
    /**
     * 控件的宽度
     */
    private float mWidth;
    /**
     * 控件的高度
     */
    private float mHeight;
    /**
     * 星星间距
     */
    private int mStarSpacing;
    /**
     * 星星总数
     */
    private int mStarTotalNum;
    /**
     * 星星个数（选择）
     */
    private float mStarNum;
    /**
     * 星星默认个数
     */
    private float mStarDefaultNum;
    /**
     *  正常、半个和选中的星星
     */
    private Bitmap mStarNormal, mStarHalf, mStarSelected;
    /**
     * 选中的资源文件
     */
    private int selectStar;
    /**
     * 未选择的资源文件
     */
    private int unselectStar;
    /**
     * 是否为指示器
     */
    private boolean isIndicator;

    /**
     * 画笔
     */
    private Paint mPaint = new Paint();

    private Animation animation;

    private OnStarChangeListener mOnStarChangeListener;

    public RatingBarView(Context context) {
        super(context);
    }

    public RatingBarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public RatingBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }


    public RatingBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    private void init(Context context ,AttributeSet attrs){
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RatingBarView);
        selectStar = array.getResourceId(R.styleable.RatingBarView_selectStarImg,R.drawable.icon_score_select);
        unselectStar = array.getResourceId(R.styleable.RatingBarView_unselectStarImg,R.drawable.icon_score_unselect);
        mStarDefaultNum = array.getInt(R.styleable.RatingBarView_defaultStarNum,1);
        mStarTotalNum = array.getInt(R.styleable.RatingBarView_starTotalNum,5);
        isIndicator = array.getBoolean(R.styleable.RatingBarView_starIndicator,false);
        mStarHeight = array.getDimension(R.styleable.RatingBarView_starHeight,dip2px(context,30));
        mStarWidth = array.getDimension(R.styleable.RatingBarView_starWidth,dip2px(context,30));
        mStarSpacing = (int) array.getDimension(R.styleable.RatingBarView_starSpacing,dip2px(context,0));
        mWidth = array.getDimension(R.styleable.RatingBarView_starHeight,dip2px(context,30));
        mHeight = array.getDimension(R.styleable.RatingBarView_starWidth,dip2px(context,30));

        mStarSelected = BitmapFactory.decodeResource(getResources(), selectStar);
        mStarNormal = BitmapFactory.decodeResource(getResources(), unselectStar);

        array.recycle();
        // 如有指定宽高，获取最大值 去改变星星的大小（星星是正方形）
        int starWidth = (int) Math.max(mStarWidth, mStarHeight);
        if (starWidth > 0) {
            mStarNormal = resetBitmap(mStarNormal, starWidth);
            mStarSelected = resetBitmap(mStarSelected, starWidth);
//            mStarHalf = resetBitmap(mStarHalf, starWidth);
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mStarNormal==null){
            return;
        }
        if (mStarSelected ==null){
            return;
        }
        // 用正常的一个星星图片去测量高
        int height = getPaddingTop() + getPaddingBottom() + mStarNormal.getHeight();
        // 宽 = 星星的宽度*总数 + 星星的间距*（总数-1） +padding
        int width = getPaddingLeft() + getPaddingRight() + mStarNormal.getWidth() * mStarTotalNum + mStarSpacing * (mStarTotalNum - 1);
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < mStarTotalNum; i++) {
            float left = getPaddingLeft();
            if (i>0){
                left = getPaddingLeft()+i*(mStarNormal.getWidth()+mStarSpacing);
            }
            float top = getPaddingTop();
            if (i < mStarNum){
                setScale();
                canvas.drawBitmap(bitMapDisplay, left, top, mPaint);

            }else {
                canvas.drawBitmap(mStarNormal, left, top, mPaint);
            }
        }
    }

    Matrix mMatrix = new Matrix();
    float mAngle = 0.0f;
    float mScale = 1f;//1为原图的大小
    Bitmap bitMapDisplay = null;

    // 缩小图片
    public void setNarrow() {
        if (mScale > 1.2f) {
            mScale -= 0.1;
            setScale();
        }
    }
    // 放大图片
    public void setEnlarge() {
        if (mScale < 1) {
            mScale += 0.1;
            setScale();
        }
    }

    // 设置旋转比例
    public void setScale() {
        mMatrix.reset();
        //float sx X轴缩放
        //float sy Y轴缩放
        mMatrix.postScale(mScale, mScale);
        bitMapDisplay = Bitmap.createBitmap(mStarSelected, 0, 0, mStarSelected.getWidth(),
                mStarSelected.getHeight(), mMatrix, true);
    }


    public static int dip2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5F);
    }

    /**
     * 如果用户设置了图片的宽高，就重新设置图片
     */
    public Bitmap resetBitmap(Bitmap bitMap, int startWidth) {
        // 得到新的图片
        return Bitmap.createScaledBitmap(bitMap, startWidth, startWidth, true);
    }

    /**
     * 设置星星的总数量
     */
    public void setStartTotalNumber(int startTotalNumber){
        if (startTotalNumber>0){
            mStarTotalNum = startTotalNumber;
            invalidate();
        }
    }

    /**
     * 设置星星的总数量
     */
    public void setSelectStartNumber(int selectStarNum){
        if (selectStarNum>0 && selectStarNum<=mStarTotalNum){
            mStarNum = selectStarNum;
            invalidate();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_MOVE:
                // 获取用户触摸的x位置
                float x = event.getX();
                //一个星星的所占的宽度
                int starX = getWidth()/mStarTotalNum;
                //计算当前触摸在第几个星星上面
                int position = (int) ((x/starX)+1);
                if (position<0){
                    position = 0;
                }
                if (position>mStarTotalNum){
                    position = mStarTotalNum;
                }
                //计算当前是否超过半个星星的宽度 如果超过则变成一个 没超过则为0个
                float result = x - starX * (position-1);
                if (result > starX * 0.5f){
                    mStarNum = position;
                }else {
                    mStarNum = position-1;
                }

                ValueAnimator anim = ValueAnimator.ofFloat(1,1.5f);

//                anim.setRepeatCount(ValueAnimator.INFINITE);//设置无限重复
//                anim.setRepeatMode(ValueAnimator.REVERSE);//设置重复模式
                anim.setDuration(500);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        mScale = (Float) animation.getAnimatedValue();
                        postInvalidate();
                    }
                });
                anim.start();
//                invalidate();
                if (mOnStarChangeListener!=null){
                    position = (int) mStarNum;
                    mOnStarChangeListener.onStarChange(mStarNum,position);
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 回调监听（选中的数量，位置）
     */
    public interface OnStarChangeListener {
        void onStarChange(float selectNum,int position);
    }

    public void setOnChangeListener(OnStarChangeListener listener) {
        mOnStarChangeListener = listener;
    }
}
